package com.rdgzs.framework.utilsTools;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public class EncryptUtils {
	// MD5是16位,SHA是20位（这是两种报文摘要的算法） 定义两种加密算法的类  
	private static final String MD5_ALGORITHM = "MD5";
	private static final String SHA_1_ALGORITHM = "SHA-1";
	private static final String UTF8 = "UTF-8";
	private static final int HEX_NUM = 16;
    private static final String[] HEX_DIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
        "e", "f" };
	private static final String PWD_FILE = "c:\\pwd.txt";
	
	public static void main(String[] args) throws Exception {
		String md5=MD5("admin","N4uDT3");
		System.out.println(md5);
	}
	
	/**
	 * md5 加密原文
	 * @param original 加密码内容
	 * @return 加密码的字段串
	 */
	public static String MD5(String original) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		return MD5(original, null);
	}
	
	/**
	 * 根据救盐值跟原文 加密
	 * @param original 加密码内容
	 * @param salt 盐值
	 * @return 加密码的字段串
	 */
	public static String MD5(String original, String salt) {
		byte tmp[]=null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (salt != null && salt.trim().length() > 0) {
				md.update(salt.getBytes("UTF-8"));
			}
			md.update(original.getBytes("UTF-8"));
			tmp = md.digest();
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("加密失败");
		}
		return byte2hex(tmp);
	}
	
	/**
	 * 将byte 转为两位的十六进制  
	 * 将数据转化为16进制进行保存，因为有些byte是不能打印的字符 单字节转化
	 * @param bin
	 * @return
	 */
	public static String byte2hex(byte[] bin) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < bin.length; ++i) {
			buf.append(byte2hex(bin[i]));
		}
		return buf.toString();
	}
	
	/**
	 * 将单个字节转为十六进制
	 * @param b
	 * @return
	 */
	public static char[] byte2hex(byte b) {
		char[] chars = new char[2];
		int x = b & 0xFF, h = x >>> 4, l = x & 0x0F;
		chars[0] = (char) (h + ((h < 10) ? '0' : 'a' - 10));
		chars[1] = (char) (l + ((l < 10) ? '0' : 'a' - 10));
		return chars;
	}
	
	public byte[] encrypt(String message) throws NoSuchAlgorithmException, IOException {
		// 加密  
		MessageDigest encrypt = MessageDigest.getInstance(MD5_ALGORITHM);
		// 添加需要加密的信息  
		encrypt.update(message.getBytes());
		// 对信息信息加密  
		byte[] encryptMD5 = encrypt.digest();
		//获得加密算法  
		System.out.println(encrypt.getAlgorithm());
		//得到加密算法的长度  
		System.out.println(encrypt.getDigestLength());
		return encryptMD5;
	}
	
	/**
	 * 将数据转化为BASE64码进行保存 
	 * @param encryptMD5
	 * @return
	 */
	public String transform(byte[] encryptMD5) {
		//对数据进行base64转发，有可能某些byte是不可打印的字符。   
		BASE64Encoder basEncoder = new BASE64Encoder();
		return basEncoder.encode(encryptMD5);
	}
	
}
